package com.base.cn.platform.os.service.integralgood;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.action.ActionKey;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.dao.integralgood.IntegralGoodDao;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.integralgood.IntegralExchangeRecord;
import com.base.cn.platform.os.entity.integralgood.IntegralGood;
import com.base.cn.platform.os.entity.integralgood.IntegralShopType;
import com.base.cn.platform.os.entity.user.address.CusUserAddress;
import com.base.cn.platform.os.entity.user.integral.CusUserIntegral;
import com.base.cn.platform.os.entity.user.integral.IntegralRule;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.base.cn.platform.os.service.manage.order.goods.OrderService;
import com.base.cn.platform.os.service.manage.user.account.CusUserAccountService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralRuleService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralService;
import com.base.cn.platform.os.service.op.coupon.OpCouponBiz;
import com.base.cn.platform.os.service.op.giftcard.OpGiftCardBiz;
import com.base.cn.platform.os.service.user.address.CusUserAddressBiz;
import com.base.cn.platform.os.service.user.integral.CusUserIntegralBiz;
import com.base.cn.platform.os.service.user.integral.IntegralRuleBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Author: Hello豆包
 * @Date: 2019/10/18 14:498
 */
@Service
public class IntegralGoodBiz extends BaseBiz<IntegralGood,IntegralGoodDao> {
    @Autowired
   private OpCouponBiz opCouponBiz;
    @Autowired
   private OpGiftCardBiz opGiftCardBiz;
    @Autowired
   private CourseService courseService;
    @Autowired
    private   OrderService orderService;
    @Autowired
    private  IntegralCardVoucherBiz integralCardVoucherBiz;

    @Autowired
    private CusUserIntegralBiz cusUserIntegralBiz;
    @Autowired
    private  IntegralExchangeRecordBiz integralExchangeRecordBiz;

    @Autowired
    private CusUserIntegralService cusUserIntegralService;
    @Autowired
    private IntegralRuleBiz integralRuleBizl;

    @Autowired
    private   CusUserAccountService cusUserAccountService;

    @Autowired
    private CusUserAddressBiz cusUserAddressBiz;

    @Autowired
    private CusUserIntegralRuleService cusUserIntegralRuleService;

    @Autowired
    private  IntegralVirtualGoodBiz integralVirtualGoodBiz;

    /**
     * 更新库存
     * @param id
     * @return
     */
    public   IntegralGood upDateInventory(BigDecimal id, Integer num){
        ArrayList<String> strings = new ArrayList<>();
        strings.add("id");
        strings.add("inventory");
        IntegralGood byId = this.findById(id,strings);
        byId.setInventory(byId.getInventory()+num);
        this.updateById(byId,null);
        return byId ;

    }

    /**
     * 根据ID查询
     * @param id
     * @param isSetShopData
     * @return
     */
    public   IntegralGood findById(BigDecimal id, boolean isSetShopData){
        IntegralGood byId = this.findById(id);
        setShopData(byId,isSetShopData);
        return byId ;

    }


    /**
     * 分页数据
     * @param page
     * @param integralGood
     * @return
     */
    public PageInfo<IntegralGood>findListPage(Pagination page,IntegralGood integralGood){
        return this.findPage(whereSql(integralGood), page, null);
    }



    /**
     * 兑换现金
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public Map redeemedCash(BigDecimal userId,Integer cash){

       if(ObjectUtils.isEmpty(cash)||cash<=0){
                return ResultUtil.ERROR("请填写兑换的金额");
        }
            //获取积分规则
        IntegralRule integralRuleByKey = integralRuleBizl.getIntegralRuleByKey(ActionKey.RATIO);
        TreeMap<String, String> contextTreeMap = integralRuleByKey.getContextTreeMap();
        int integral = Integer.parseInt(contextTreeMap.get("integral"));
        double money = Double.parseDouble(contextTreeMap.get("money"));
        double result =money/integral;

        //计算积分用户积分是否满
        CusUserIntegral cusUserIntegral = cusUserIntegralBiz.queryUserIntegralByUserId(userId);
        Integer currentScore = cusUserIntegral.getCurrentScore();
        if(cash<integral){
            IntegralRule userIntegralRuleName= cusUserIntegralRuleService.getUserIntegralRuleByKey(ActionKey.NAME);
            TreeMap<String, String> contextTreeMap4 = userIntegralRuleName.getContextTreeMap();
            String name = contextTreeMap4.get("name");
            return ResultUtil.ERROR( new StringBuilder("兑换数不能小于").append(integral).append(name).toString());
        }
        if(cash>currentScore){
            IntegralRule userIntegralRuleName= cusUserIntegralRuleService.getUserIntegralRuleByKey(ActionKey.NAME);
            TreeMap<String, String> contextTreeMap4 = userIntegralRuleName.getContextTreeMap();
            String name = contextTreeMap4.get("name");
            return ResultUtil.ERROR( new StringBuilder(name).append("不足").toString());
        }
        DecimalFormat df = new DecimalFormat("#,##0.#");
            //校验通过
        double v = Double.parseDouble(df.format(result * cash));
        Map map = giveCash(userId, v, cash);
        if(ResultUtil.getSuccess(map)){
            IntegralExchangeRecord integralExchangeRecord = (IntegralExchangeRecord) ResultUtil.getEntity(map);
            integralExchangeRecordBiz.save(integralExchangeRecord);
            //扣除积分
            cusUserIntegralService.addUserIntegral(ActionKey.MONEY,userId,null,cash,1);
            CusUserIntegral cusUserIntegral1 = new CusUserIntegral();
            cusUserIntegral1.setId(cusUserIntegral.getId());
            cusUserIntegral1.setChangeAmount(cusUserIntegral.getChangeAmount()+v);
            cusUserIntegralBiz.updateById(cusUserIntegral1,null);
        }else{
            return  map;
        }
        return  ResultUtil.SUCCESS("兑换成功");
    }
    /**
     * 兑换商品
     * @param userId
     * @param shopId
     * @return
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public Map exchangeIntegralShop(BigDecimal userId, BigDecimal shopId){

        IntegralGood byId = findById(shopId, false);
        //检查是否是实体商品
        CusUserAddress addresssEntity =  null;
        if(byId.getShopType().equals(IntegralShopType.ENTITY)){
            CusUserAddress cusUserAddress = new CusUserAddress();
            cusUserAddress.setUserId(userId);
            cusUserAddress.setStatus(1);
            List<CusUserAddress> cusUserAddresses = cusUserAddressBiz.queryUserAddressList(cusUserAddress, true);
            if(ObjectUtils.isEmpty(cusUserAddresses)){
                return   ResultUtil.ERROR("请先创建收获地址",10002);
            }
            addresssEntity =cusUserAddresses.get(0);
        }
        CusUserIntegral cusUserIntegral = cusUserIntegralBiz.queryUserIntegralByUserId(userId);
        //验证用户积分是否可以兑换商品
        Integer currentScore = cusUserIntegral.getCurrentScore();
        Integer integral = byId.getIntegral();
        if(currentScore==0||currentScore<integral){
            IntegralRule userIntegralRuleName= cusUserIntegralRuleService.getUserIntegralRuleByKey(ActionKey.NAME);
            TreeMap<String, String> contextTreeMap4 = userIntegralRuleName.getContextTreeMap();
            String name = contextTreeMap4.get("name");

            return ResultUtil.ERROR( new StringBuilder("抱歉，您的").append(name).append("不不足以兑换该物品，快快赚取积分").append(name).append("吧").toString());
        }
        if(ObjectUtils.isEmpty(byId.getInventory())||byId.getInventory()==0){
            return  ResultUtil.ERROR("抱歉，商品兑换完了");
        }
            Map map = distributionOfGoods(byId, userId);
            if(ResultUtil.getSuccess(map)){
                IntegralGood integralGood = new IntegralGood();
                integralGood.setId(byId.getId());
                //创建记录
                if(byId.getInventory()>0){
                    integralGood.setInventory(byId.getInventory()-1);
                }
                if(byId.getShopType().equals(IntegralShopType.ENTITY)){
                    integralGood.setNotDeliverNum(byId.getNotDeliverNum()+1);
                }
                integralGood.setExchangeNum(byId.getExchangeNum()+1);
                integralGood.setConsumptionNum(byId.getConsumptionNum()+byId.getIntegral());
                this.updateById(integralGood,null);
                IntegralExchangeRecord integralExchangeRecord = (IntegralExchangeRecord) ResultUtil.getEntity(map);
                //设置实体商品收获地址
                if(ObjectUtils.isNotEmpty(addresssEntity)){
                    StringBuilder address = new StringBuilder();
                    if(ObjectUtils.isNotEmpty(addresssEntity.getProvince())){
                        address.append(addresssEntity.getProvince().getAreaName());
                    }
                    if(ObjectUtils.isNotEmpty(addresssEntity.getCity())){
                        address.append(addresssEntity.getCity().getAreaName());
                    }
                    if(ObjectUtils.isNotEmpty(addresssEntity.getTown())){
                        address.append(addresssEntity.getTown().getAreaName());
                    }
                        address.append(addresssEntity.getAddress());
                        integralExchangeRecord.setAddress(address.toString());
                }
                integralExchangeRecordBiz.save(integralExchangeRecord);
                //扣除积分
                CusUserIntegral cusUserIntegral1 = new CusUserIntegral();
                cusUserIntegral1.setId(cusUserIntegral.getId());
                cusUserIntegral1.setExchangeNum(cusUserIntegral.getExchangeNum()+1);
                cusUserIntegralBiz.updateById(cusUserIntegral1,null);
                cusUserIntegralService.addUserIntegral(ActionKey.GOODS,userId,null,byId.getIntegral(),1);

            }else{
                return map;
            }
        return ResultUtil.SUCCESS("兑换成功");
    }


    /**
     * 发放商品
     * @param entity
     * @param userId
     * @return
     */
    private Map distributionOfGoods(IntegralGood entity,BigDecimal userId){
        Map result = null;
                //发放用户商品
        String shopType = entity.getShopType();
        switch (shopType){
            case IntegralShopType.COUPON:
                //赠送优惠券
                result = opCouponBiz.exchangeCoupon(userId, entity.getShopId());
                break;
            case IntegralShopType.COURSE:
                result = orderService.exchangeFreeOrder(userId, entity.getShopId() + "-COURSE-1");
                break;
            case IntegralShopType.ENTITY:
                //实体商品不需要处理任何商品
                result =ResultUtil.SUCCESS();
                break;
            case IntegralShopType.GIFT_CARD:
                result =  opGiftCardBiz.exchangeGiftCard(userId,entity.getShopId());
                break;
            case IntegralShopType.VIRTUAL_GOODS:
                result=   integralCardVoucherBiz.exchangeIntegralCardVoucher(userId,entity.getShopId(),entity.getId());
                break;

            default:
                return  ResultUtil.ERROR("兑换商品信息有误请联系客服");
        }
        if(ResultUtil.getSuccess(result)){
                //创建兑换记录
            IntegralExchangeRecord integralExchangeRecord = new IntegralExchangeRecord();
            integralExchangeRecord.setName(entity.getName());
            integralExchangeRecord.setIntegral(entity.getIntegral());
            integralExchangeRecord.setNotDeliver(0);
            integralExchangeRecord.setShopId(entity.getShopId());
            integralExchangeRecord.setShopType(shopType);
            integralExchangeRecord.setIntegralShopId(entity.getId());
            integralExchangeRecord.setUserId(userId);


            if(!shopType.equals(IntegralShopType.COURSE)&&!shopType.equals(IntegralShopType.ENTITY)&&ObjectUtils.isNotEmpty(ResultUtil.getEntity(result))){
                integralExchangeRecord.setShopIdReal(new BigDecimal(ResultUtil.getEntity(result).toString()));
            }
            return  ResultUtil.SUCCESS("兑换成功",integralExchangeRecord);
        }else{
            return result;
        }
    }


    /**
     * 发放现金
     * @param userId
     * @param cash
     * @return
     */
    private Map giveCash(BigDecimal userId,Double  cash,Integer consumptionIntegral){


        Map<String, Object> cusUserAccount = cusUserAccountService.userAccountInfo(userId, false);

        Map<String, Object>  addResult = cusUserAccountService.updateUserAccountAmount(userId, new BigDecimal(cusUserAccount.get("id").toString()), 11, cash);

        if(ResultUtil.getSuccess(addResult)){
            //创建兑换记录
            IntegralExchangeRecord integralExchangeRecord = new IntegralExchangeRecord();
            integralExchangeRecord.setName("现金兑换");
            integralExchangeRecord.setIntegral(consumptionIntegral);
            integralExchangeRecord.setNotDeliver(0);
            integralExchangeRecord.setExchangeCash(new BigDecimal(cash));
            integralExchangeRecord.setShopType(IntegralShopType.CASH);
            integralExchangeRecord.setUserId(userId);
            return  ResultUtil.SUCCESS("兑换成功",integralExchangeRecord);
        }else{
                return  addResult;
        }

    }



    /**
     * 设置商品数据
     * @param byId
     * @param isSetShopData
     */
    private  void setShopData(IntegralGood byId,boolean isSetShopData){
        if(isSetShopData&&ObjectUtils.isNotEmpty(byId)){
            switch(byId.getShopType()){
                case IntegralShopType.COUPON:
                    byId.setOpCoupon(opCouponBiz.findById(byId.getShopId()));
                    break;
                case IntegralShopType.COURSE:
                    Course courseById =  courseService.findByIdCourse(byId.getShopId());
                    byId.setCourse(courseById);
                    break;
                case IntegralShopType.GIFT_CARD:
                    byId.setOpGiftCard(opGiftCardBiz.findById(byId.getShopId()));
                   break;
                case IntegralShopType.VIRTUAL_GOODS:
                    byId.setIntegralVirtualGood(integralVirtualGoodBiz.findById(byId.getShopId()));
                    break;
                default:
                    break;
                }
                if(!byId.getShopType().equals(IntegralShopType.ENTITY)){
                    getShopData(byId);
                }
        }
    }


    /**
     * 获取 shopData
     * @return
     */
    private void getShopData(IntegralGood entity){
        HashMap<String, Object> obj = null;
        String name = "";
        switch( entity.getShopType()){
            case IntegralShopType.COUPON:
                if(ObjectUtils.isNotEmpty( entity.getOpCoupon())){
                    name =    entity.getOpCoupon().getTitle();
                }

                break;
            case IntegralShopType.COURSE:
                if(ObjectUtils.isNotEmpty( entity.getCourse())){
                    name =   entity.getCourse().getCourseName();
                }
                break;
            case IntegralShopType.GIFT_CARD:
                if(ObjectUtils.isNotEmpty( entity.getOpGiftCard())){
                    name =  entity.getOpGiftCard() .getCardName();
                }
                break;
            case IntegralShopType.VIRTUAL_GOODS:
                if(ObjectUtils.isNotEmpty( entity.getIntegralVirtualGood())){
                    name =  entity.getIntegralVirtualGood().getName();
                }
                break;
            default:
                break;
        }
        if(StringUtils.isNotEmpty(name)){
            obj =    new HashMap<>();
            obj.put("name",name);
        }
        entity.setShopData(obj);
    }
    /**
     * sql
     * @param integralGood
     * @return
     */
    private String whereSql(IntegralGood integralGood){
        StringBuilder sql = new StringBuilder(" status !=4");
        if(ObjectUtils.isNotEmpty(integralGood)){
            if(StringUtils.isNotEmpty(integralGood.getName())){
                sql.append(" and name like '%").append(integralGood.getName()).append("%'");
            }
            if(ObjectUtils.isNotEmpty(integralGood.getType())){
                sql.append(" and type = ").append(integralGood.getType());
            }
            if(ObjectUtils.isNotEmpty(integralGood.getStatus())){
                sql.append(" and status = ").append(integralGood.getStatus());
            }
        }
        return  sql.toString();
    }
}
